package algotithm.leetcode.listnode.test725;

import algotithm.leetcode.listnode.ListNode;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/22-22:56
 * @URL https://leetcode-cn.com/problems/split-linked-list-in-parts/
 * @Title 725. 分隔链表
 */
class Solution {
    public ListNode[] splitListToParts(ListNode root, int k) {
        ListNode cur = root;
        int N = 0;
        while (cur != null) {
            cur = cur.next;
            N++;
        }

        int width = N / k, rem = N % k;

        ListNode[] ans = new ListNode[k];
        cur = root;
        for (int i = 0; i < k; ++i) {
            ListNode head = cur;
            for (int j = 0; j < width + (i < rem ? 1 : 0) - 1; ++j) {
                if (cur != null) {
                    cur = cur.next;
                }
            }
            if (cur != null) {
                ListNode prev = cur;
                cur = cur.next;
                prev.next = null;
            }
            ans[i] = head;
        }
        return ans;
    }
}


